package com.luyun.frogpay.base.baseclass;

import android.accounts.NetworkErrorException;
import android.content.Context;

import com.luyun.frogpay.base.utils.Log;

import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;


/**
 * Created by 赵星宇 on 2018/1/26.
 *
 */

public abstract class BaseObserver<T> implements Observer<BaseResponse<T>> {
    protected Context context;

    public BaseObserver(Context context) {
        this.context = context;
    }

    public BaseObserver() {

    }
    @Override
    public void onSubscribe(Disposable d) {
        onRequestStart();
    }

    @Override
    public void onNext(BaseResponse<T> baseResponse) {
        Log.d("onNext");
        onRequestEnd();
        if (baseResponse.isSuccess()) {
            Log.d("成功："+ baseResponse.isSuccess());
            try {
                onSuccees(baseResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            Log.d("失败："+ baseResponse.isSuccess());
            try {
                onCodeError(baseResponse);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    public void onError(Throwable e) {
        Log.d("onError");
        onRequestEnd();
        try {
            if(e instanceof ConnectException){
                onFailure("连接错误", true);
            }else if(e instanceof TimeoutException){
                onFailure("连接超时", true);
            }else if(e instanceof NetworkErrorException){
                onFailure("网络错误", true);
            }else if(e instanceof UnknownHostException){
                onFailure("请求错误", true);
            }else {
                onFailure(e.getMessage(), false);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    @Override
    public void onComplete() {
    }

    /**
     * 返回成功
     * @param t
     * @throws
     */
    protected abstract void onSuccees(BaseResponse<T> t) throws Exception;

    /**
     * 返回成功了,但是code错误
     * @param t
     * @throws
     */
    protected abstract void onCodeError(BaseResponse<T> t) throws Exception;

    /**
     * 返回失败
     * @param errorMsg
     * @param isNetWorkError 是否是网络错误
     * @throws
     */
//    protected abstract void onFailure(Throwable e, boolean isNetWorkError) throws Exception;
    protected abstract void onFailure(String errorMsg, boolean isNetWorkError) throws Exception;

    protected void onRequestStart() {
    }

    protected void onRequestEnd() {
    }

    public void showProgressDialog() {
    }

    public void closeProgressDialog() {
    }
}
